﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SCRUM.Core.DAO;
using SCRUM.Core.BusinessObjects;
using System.Collections.Specialized;
using SCRUM.Core.MembershipProviders;

/// <summary>
/// Widget for scrum master to keep track of all the activity inside the team for specific daily scrum meeting
/// </summary>
public partial class DailyScrumWidget : DataOverviewWidget<DailyScrum>
{/// <summary>
    /// Gets the name of the widget. It must be exactly the same as the folder that contains the widget.
    /// </summary>
    /// <value></value>
    public override string Name
    {
        get { return "DailyScrumWidget"; }
    }

    /// <summary>
    /// Gets the title. Title is shown in the header of the widget container.
    /// </summary>
    /// <value>The title.</value>
    public override string Title
    {
        get { return (string)GetLocalResourceObject("Title"); }
    }

    #region [MARTIN BLE]
    /*
    

    /// <summary>
    /// Method to catch all commands on the AllData grid.
    /// </summary>
    /// <param name="sender">sender</param>
    /// <param name="e">command arguments - name, selected row,...</param>
    public void handleRowCommand(Object sender, GridViewCommandEventArgs e)
    {
        //command to highlight row and show details of selected entity
        if (e.CommandName == "NameClicked")
        {
            hideAllDetails();
            //returns selected row
            int row = System.Convert.ToInt32(e.CommandArgument);
            if (row != -1)
            {
                //show project detail
                DailyScrum ds = daily.ElementAt(row);
                DailyDetails.tasks = DAOTask.GetAllUsersTasks(users[selectedUserIndex].ID);
                DailyDetails.forUser = users[selectedUserIndex];
                DailyDetails.showDailyScrumDetails(ds);
                DailyDetails.Visible = true;
                ButtonsDiv.Visible = false;
                AllData.SelectedIndex = row;
                OkDiv.Visible = true;
                EditBtn.Visible = true;
                OkBtn.Visible = false;
                DeleteBtn.Visible = true;
            }
        }
    }


    /// <summary>
    /// Saves settings from DivEdit and hides edit.
    /// </summary>
    /// <param name="sender">sender</param>
    /// <param name="e">arguments</param>
    protected void LinkButtonSave_Click(object sender, EventArgs e)
    {
        //save config
        saveColumnDefSetting();
        hideAllDetails();
        LoadWidget();
    }

    

    /// <summary>
    /// Loads data according to settings
    /// </summary>
    private void refreshData()
    {
        if (users.Count>0 && selectedUserIndex != -1)
        {
            User usr = users[selectedUserIndex];
            daily = DaoDailyScrum.GetAlldailyScrumDetails(usr);
            AllData.DataSource = daily;
            AllData.DataBind();
            AllData.Visible = true;
            DailyDetails.Visible = false;
        }
    }

    /// <summary>
    /// Hides all detail divs
    /// </summary>
    private void hideAllDetails()
    {
        DailyDetails.Visible = false;
        OkDiv.Visible = false;
        AllData.SelectedIndex = -1;
    }

    /// <summary>
    /// Creates new entity
    /// </summary>
    /// <param name="sender">sender</param>
    /// <param name="e">arguments</param>
    protected void CreateBtn_Click(object sender, EventArgs e)
    {
        DailyDetails.tasks = DAOTask.GetAllUsersTasks(users[selectedUserIndex].ID);
        DailyDetails.forUser = users[selectedUserIndex];
        DailyScrum ds = new DailyScrum(0, DateTime.Now, users[selectedUserIndex]);
        DailyDetails.showDailyScrumDetails(ds);
        OkDiv.Visible = true;
        EditBtn.Visible = false;
        OkBtn.Visible = true;
        DeleteBtn.Visible = false;
    }

    /// <summary>
    /// Updates selected entity
    /// </summary>
    /// <param name="sender">sender</param>
    /// <param name="e">arguments</param>
    protected void EditBtn_Click(object sender, EventArgs e)
    {
        if (AllData.SelectedIndex != -1)
        {
            DailyDetails.tasks = DAOTask.GetAllUsersTasks(users[selectedUserIndex].ID);
            DailyDetails.forUser = users[selectedUserIndex];
            DailyScrum dsOld = (DailyScrum)daily[AllData.SelectedIndex];
            DailyDetails.editDailyScrum(dsOld.ID);
            DailyDetails.Visible = false;
            refreshData();
            hideAllDetails();
        }
    }

    /// <summary>
    /// Deletes selected entity
    /// </summary>
    /// <param name="sender">sender</param>
    /// <param name="e">arguments</param>
    protected void DeleteBtn_Click(object sender, EventArgs e)
    {
        if (AllData.SelectedIndex != -1)
        {
            DailyDetails.deleteDailyScrum(daily[AllData.SelectedIndex]);
            hideAllDetails();
            refreshData();
        }
    }

    /// <summary>
    /// Confirmed createion of new entity
    /// </summary>
    /// <param name="sender">sender</param>
    /// <param name="e">arguments</param>
    protected void OkBtn_Click(object sender, EventArgs e)
    {
        DailyDetails.tasks = DAOTask.GetAllUsersTasks(users[selectedUserIndex].ID);
        DailyDetails.forUser = users[selectedUserIndex];
        DailyDetails.createNewDailyScrum();
        refreshData();
        hideAllDetails();
    }

    protected void CancelBtn_Click(object sender, EventArgs e)
    {
        hideAllDetails();
    }

    protected void AllData_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        AllData.PageIndex = e.NewPageIndex;
        AllData.DataBind();
    }

    protected void SelectedTeamChanged(object sender, EventArgs e)
    {
        //reload users
        HttpContext.Current.Session["SelectedTeamCB" + this.ID] = Teams.SelectedValue;
        //DAOWidgetSettings.SaveCreateSettings(this, "SelectedTeamCB", Teams.SelectedValue); 
        LoadWidget();
    }

    protected void SelectedUserChanged(object sender, EventArgs e)
    {
        HttpContext.Current.Session["SelectedUserCB" + this.ID] = Users.SelectedValue;
        LoadWidget();
    }
     * */
    #endregion

    #region [UserManagementWidget Settings]

    /// <summary>
    /// Gets a value indicating whether this instance is editable.
    /// </summary>
    /// <value>
    /// 	<c>true</c> if this instance is editable; otherwise, <c>false</c>.
    /// </value>
    public override bool IsEditable
    {
        get { return true; }
    }

    /// <summary>
    /// Shows the edit.
    /// </summary>
    public override void ShowEdit()
    {
        base.ShowEdit();
        this.DivEdit.Visible = true;
    }

    /// <summary>
    /// Hides the edit.
    /// </summary>
    public override void HideEdit()
    {
        base.HideEdit();
        this.DivEdit.Visible = false;
    }

    /// <summary>
    /// Occurs when user clicks on Save Settings of PrototypeWidget
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void SaveSettingsClick(object sender, EventArgs e)
    {
        SaveSettings();
        this.HideEdit();
        LoadWidget();
    }

    /// <summary>
    /// Refreshes settings section with data from private member settings
    /// </summary>
    private void ShowSettings()
    {
        LabelPageSize.Text = settings["pageSize"];
    }

    ///// <summary>
    ///// Handles the SelectedPageChanged event of the GridViewData control.
    ///// </summary>
    ///// <param name="sender">The source of the event.</param>
    ///// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewPageEventArgs"/> instance containing the event data.</param>
    //public void GridViewData_SelectedPageChanged(object sender, GridViewPageEventArgs e)
    //{
    //    GridViewData.PageIndex = e.NewPageIndex;
    //    GridViewData.DataBind();
    //}

    #endregion

    #region [OVERRIDEN]

    /// <summary>
    /// This method works as a substitute for Page_Load. You should use this method for
    /// data binding etc. instead of Page_Load.
    /// </summary>
    public override void LoadWidget()
    {
        LoadAvailableColumns();
        ApplySettings();
        if (!IsPostBack)
        {
            LoadFilter();
            RefreshWidget();
        }
    }    

    protected override IList<DailyScrum> itemsAcordingToFilter
    {
        get
        {
            IList<DailyScrum> records = new List<DailyScrum>();
            if (this.Users.SelectedIndex != -1)
            {
                int userID = Int32.Parse(this.Users.SelectedValue);
                User user = DAOUser.GetUserByID(userID);
                records = DaoDailyScrum.GetAlldailyScrumDetails(user);
            }
            return records;
        }
    }
    #endregion

    public override void RefreshWidget()
    {
        base.RefreshWidget();
        bool itemSelected = this.data.SelectedIndex != -1;
        
        SelectAndDisplayItem(this.selectedItem, itemSelected);
        //this.buttonCreate.Visible = this.filtersSuperiorItemID != -1 && this.UserRights.CanModify;
        
        bool userSelected = this.Users.SelectedIndex != -1;
        this.buttonCreate.Visible = userSelected;
        this.LabelHasTasks.Text = "";
        if(userSelected)
        {
            bool hasTasks = this.Users.SelectedIndex != -1 ? DAOTask.GetAllUsersTasks(this.SelectedUser.ID).Count != 0 : false;
            buttonCreate.Visible = hasTasks;
            this.LabelHasTasks.Text = hasTasks ? "" : (string)GetLocalResourceObject("HasNoTasks");
        }
    }

    protected virtual void SelectAndDisplayItem(DailyScrum item, bool show)
    {
        bool exists = item != null;

        if(show)
        {
            if (!exists)
            {
                item = new DailyScrum(0, DateTime.Now, SelectedUser);
            }
            EnsurePrerequisitesForDetails();
            this.itemDetails.ShowDailyScrumDetails(item);
        }

        
        this.itemDetails.Visible = show;
        //this.buttonCreateItem.Visible = show && !exists && this.UserRights.CanModify;
        //this.buttonSaveItem.Visible = show && exists && this.UserRights.CanModify;
        //this.buttonDeleteItem.Visible = show && exists && this.UserRights.CanModify;
        this.buttonCreateItem.Visible = show && !exists;
        this.buttonSaveItem.Visible = show && exists;
        this.buttonDeleteItem.Visible = show && exists;
        this.buttonCancelItem.Visible = show;
    }

    private void EnsurePrerequisitesForDetails()
    {
        this.itemDetails.tasks = DAOTask.GetAllUsersTasks(this.SelectedUser.ID);
        this.itemDetails.forUser = SelectedUser;
    }

    #region [ tommy ]

    private void LoadFilter()
    {
        // nemam este teamy pre scrummastera
        if (this.Teams.Items.Count == 0)
        {
            LoadTeams();
        }
        LoadUsers();

    }

    private void LoadTeams()
    {
        User currentUser = MembershipProviderFactory.MembershipProvider.GetUser();
        this.Teams.DataSource = DAOTeam.GetTeamForUser(currentUser);
        this.Teams.DataTextField = "Name";
        this.Teams.DataValueField = "ID";
        this.Teams.DataBind();
    }

    private void LoadUsers()
    {
        if(this.SelectedTeamID != -1)
        {
            int teamID = this.SelectedTeamID;
            Team team = DAOTeam.GetTeam(teamID);
            this.Users.DataSource = DAOUser.GetTeamMembers(team);
            this.Users.DataTextField = "FullName";
            this.Users.DataValueField = "ID";
            this.Users.DataBind();
        }
    }

    public User SelectedUser
    {
        get
        {
            int userID = Int32.Parse(this.Users.SelectedValue);
            return DAOUser.GetUserByID(userID);
        }
    }

    public int SelectedTeamID
    {
        get 
        {
            return this.Teams.SelectedIndex != -1 ? Int32.Parse(this.Teams.SelectedValue) : -1;
        }
    }
    
    protected void FilterChanged(object sender, EventArgs e)
    {
		//if (SelectedTeamID != -1)
		//{
		//    this.LoadUsers();
		//}
		RefreshWidget();
    }

    #endregion

    #region [ ITEM CONTROLS ]

    /// <summary>
    /// When user tries to create new item
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ButtonCreate_Click(object sender, EventArgs e)
    {
        SelectAndDisplayItem(null, true);
    }

    /// <summary>
    /// User tries to create new Sprint
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void ButtonCreateItem_Click(object sender, EventArgs e)
    {
        try
        {
            CreateItem();
            HideDetails();
        }
        catch (SCRUM.Core.Exceptions.Database.InconsistentDatabaseException ex)
        {
            ShowOperationResult(MessageType.Error, ex.Message);
        }
    }

    /// <summary>
    /// User tries to save selected (potentialy modified) sprint
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ButtonSaveItem_Click(object sender, EventArgs e)
    {
        try
        {
            SaveItem();
            HideDetails();
        }
        catch (SCRUM.Core.Exceptions.Database.InconsistentDatabaseException ex)
        {
            ShowOperationResult(MessageType.Error, ex.Message);
        }
    }

    /// <summary>
    /// User tries to cancel updating/creating of sprint
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ButtonCancelItem_Click(object sender, EventArgs e)
    {
        HideDetails();
    }

    /// <summary>
    /// User tries to delete item
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void ButtonDeleteItem_Click(object sender, EventArgs e)
    {
        DeleteItem_Click(selectedItem.ID);
    }

    /// <summary>
    /// Deletes selected entity
    /// </summary>
    /// <param name="sender">sender</param>
    /// <param name="ce">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
    protected void ImageButtonDeleteItem_Click(object sender, CommandEventArgs ce)
    {
        DeleteItem_Click(Int32.Parse((string)ce.CommandArgument));
    }

    protected void DeleteItem_Click(int itemID)
    {
        try
        {
            DeleteItem(itemID);
            HideDetails();
            ShowOperationResult(MessageType.Info, "DailyScrumDeleted");
        }
        catch (SCRUM.Core.Exceptions.Database.InconsistentDatabaseException ex)
        {
            ShowOperationResult(MessageType.Error, ex.Message);
        }
    }

    protected void CreateItem() 
    {
        //DailyScrum ds = new DailyScrum(0, DateTime.Now, SelectedUser);
        //itemDetails.showDailyScrumDetails(ds);
        EnsurePrerequisitesForDetails();
        itemDetails.CreateNewDailyScrum();
        ShowOperationResult(MessageType.Info, "DailyScrumCreated");
    }

    protected void SaveItem()
    {
        //itemDetails.forUser = SelectedUser;
        //itemDetails.tasks = ;
        //itemDetails.showDailyScrumDetails(this.selectedItem);
        //SelectAndDisplayItem(this.selectedItem, true);
        EnsurePrerequisitesForDetails();
        itemDetails.EditDailyScrum(this.selectedItem.ID);
        ShowOperationResult(MessageType.Info, "DailyScrumUpdated");
    }

    protected void DeleteItem(int itemID) 
    {
        itemDetails.DeleteDailyScrum(this.selectedItem);
        //if (AllData.SelectedIndex != -1)
        //{
        //    DailyDetails.deleteDailyScrum(daily[AllData.SelectedIndex]);
        //    hideAllDetails();
        //    refreshData();
        //}
    }


    protected void HideDetails()
    {
        data.SelectedIndex = -1;
        RefreshWidget();
    }

    /// <summary>
    /// Handles the PreRender event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_PreRender(object sender, EventArgs e)
    {
        base.Page_PreRender(sender, e);
        if (this.Teams.Items.Count == 0)
        {
            ShowOperationResult(MessageType.Warning, "DailyScrumNotInTeam");
        }
        this.DailyScrumContent.Visible = this.Teams.Items.Count != 0;
    }

    #endregion

    protected override int alwaysVisibleColumn { get { return 1; } }
    protected override GridView data { get { return this.AllData; } }
    protected override Panel availableColumnsPanel { get { return this.AvailableColumns; } }
    protected override TextBox textBoxPageSize { get { return this.TextBoxPageSize; } }
}